<template>
  <div class="user-info-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="个人信息"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 信息列表 -->
    <div class="info-list">
      <van-cell-group>
        <van-cell title="头像" is-link center @click="$router.push('/user')">
          <template #value>
            <van-image
              round
              width="40"
              height="40"
              :src="userInfo.pic || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
            />
          </template>
        </van-cell>
        <van-cell 
          title="昵称" 
          is-link 
          :value="userInfo.name || '未设置'"
          @click="showNamePopup"
        />
        <van-cell 
          title="性别" 
          is-link 
          :value="userInfo.sex === 1 ? '男' : userInfo.sex === 2 ? '女' : '保密'"
          @click="showGenderPopup"
        />
        <van-cell 
          title="手机号" 
          :value="formatPhone(userInfo.mobile)"
          is-link
          @click="showPhonePopup"
        />
        <van-cell 
          title="修改密码" 
          is-link
          @click="showPasswordPopup"
        />
      </van-cell-group>
    </div>

    <!-- 修改昵称弹窗 -->
    <van-popup v-model:show="showName" position="bottom" round>
      <div class="popup-content">
        <div class="popup-header">
          <span>修改昵称</span>
          <van-icon name="cross" @click="showName = false" />
        </div>
        <div class="popup-body">
          <van-field
            v-model="newName"
            placeholder="请输入昵称"
            maxlength="20"
          />
          <van-button type="primary" block @click="updateName">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 修改手机号弹窗 -->
    <van-popup v-model:show="showPhone" position="bottom" round>
      <div class="popup-content">
        <div class="popup-header">
          <span>修改手机号</span>
          <van-icon name="cross" @click="showPhone = false" />
        </div>
        <div class="popup-body">
          <van-field
            v-model="newPhone"
            type="tel"
            maxlength="11"
            placeholder="请输入新手机号"
          />
          <van-field
            v-model="smsCode"
            center
            clearable
            placeholder="请输入验证码"
          >
            <template #button>
              <van-button 
                size="small" 
                type="primary" 
                :disabled="isCountingDown"
                @click="sendCode"
              >
                {{ countDownText }}
              </van-button>
            </template>
          </van-field>
          <van-button type="primary" block @click="updatePhone">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 修改密码弹窗 -->
    <van-popup v-model:show="showPassword" position="bottom" round>
      <div class="popup-content">
        <div class="popup-header">
          <span>修改密码</span>
          <van-icon name="cross" @click="showPassword = false" />
        </div>
        <div class="popup-body">
          <van-field
            v-model="oldPassword"
            type="password"
            placeholder="请输入原密码"
          />
          <van-field
            v-model="newPassword"
            type="password"
            placeholder="请输入新密码"
          />
          <van-field
            v-model="confirmPassword"
            type="password"
            placeholder="请确认新密码"
          />
          <van-field
            v-model="passwordSmsCode"
            center
            clearable
            placeholder="请输入验证码"
          >
            <template #button>
              <van-button 
                size="small" 
                type="primary" 
                :disabled="isPasswordCountingDown"
                @click="sendPasswordCode"
              >
                {{ passwordCountDownText }}
              </van-button>
            </template>
          </van-field>
          <van-button type="primary" block @click="updatePassword">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 性别选择弹窗 -->
    <van-popup v-model:show="showGender" position="bottom" round>
      <van-picker
        :columns="genderColumns"
        @confirm="onGenderConfirm"
        @cancel="showGender = false"
        :title="'选择性别'"
        show-toolbar
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showDialog, showToast } from 'vant'
import { updateUserName, updateUserGender, updateUserMobile, getMoblieMsg, updatePassword as updateUserPassword } from '@/api/user/user'


const router = useRouter()
const userInfo = ref({})

// 弹窗控制
const showName = ref(false)
const showGender = ref(false)
const newName = ref('')
const newPhone = ref('')
const smsCode = ref('')
const countdown = ref(0)
const showPhone = ref(false)
const isCountingDown = computed(() => countdown.value > 0)
const countDownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}秒后重试` : '获取验证码'
})

// 密码相关变量
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const passwordSmsCode = ref('')
const showPassword = ref(false)
const passwordCountdown = ref(0)
const isPasswordCountingDown = computed(() => passwordCountdown.value > 0)
const passwordCountDownText = computed(() => {
  return isPasswordCountingDown.value ? `${passwordCountdown.value}秒后重试` : '获取验证码'
})

// 获取用户信息
onMounted(() => {
  const userStr = sessionStorage.getItem('user')
  if (userStr) {
    userInfo.value = JSON.parse(userStr)
  }
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 显示修改昵称弹窗
const showNamePopup = () => {
  newName.value = userInfo.value.name || ''
  showName.value = true
}

// 修改性别相关变量
const genderColumns = [
  { text: '男', value: 1 },
  { text: '女', value: 2 },
  { text: '保密', value: 0 }
]

const genderText = computed(() => {
  switch(userInfo.value.gender) {
    case 1: return '男'
    case 2: return '女'
    default: return '保密'
  }
})

// 修改性别选择确认方法
const onGenderConfirm = async (selectedOption) => {
  try {
    // 打印完整的选择项和请求参数，用于调试
    // console.log('Selected Option:', selectedOption)
    const requestData = {
      id: userInfo.value.id,
      sex: selectedOption.selectedOptions[0].value
    }
    // console.log('Request Data:', requestData)

    const res = await updateUserGender(requestData)
    if (res.code === 200) {
      userInfo.value.sex = selectedOption.selectedOptions[0].value
      sessionStorage.setItem('user', JSON.stringify(userInfo.value))
      showToast('修改成功')
    } else {
      showToast(res.message || '修改失败')
    }
  } catch (error) {
    console.error('Update gender error:', error)
    showToast('修改失败')
  }
  showGender.value = false
}

// 显示性别选择弹窗
const showGenderPopup = () => {
  showGender.value = true
}

// 格式化手机号
const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 显示修改手机号弹窗
const showPhonePopup = () => {
  newPhone.value = ''
  smsCode.value = ''
  showPhone.value = true
}

// 发送验证码
const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(newPhone.value)) {
    showToast('请输入正确的手机号')
    return
  }
  
  try {
    let res = await getMoblieMsg(newPhone.value)
    if(res.code === 200) {
      showToast('验证码已发送')
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    showToast('发送失败，请重试')
  }
}

// 更新手机号
const updatePhone = async () => {
  if (!/^1[3-9]\d{9}$/.test(newPhone.value)) {
    showToast('请输入正确的手机号')
    return
  }
  if (!smsCode.value) {
    showToast('请输入验证码')
    return
  }
  
  try {
    let res = await updateUserMobile({
      id: userInfo.value.id,
      mobile: newPhone.value,
      mobileCode: smsCode.value
    })
    if(res.code === 200) {
      userInfo.value.mobile = newPhone.value
      sessionStorage.setItem('user', JSON.stringify(userInfo.value))
      showToast('修改成功')
      showPhone.value = false
    }
  } catch (error) {
    showToast('修改失败')
  }
}

// 显示修改密码弹窗
const showPasswordPopup = () => {
  oldPassword.value = ''
  newPassword.value = ''
  confirmPassword.value = ''
  passwordSmsCode.value = ''
  showPassword.value = true
}

// 发送密码修改验证码
const sendPasswordCode = async () => {
  try {
    let res = await getMoblieMsg(userInfo.value.mobile)
    if(res.code === 200) {
      showToast('验证码已发送')
      passwordCountdown.value = 60
      const timer = setInterval(() => {
        passwordCountdown.value--
        if (passwordCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    showToast('发送失败，请重试')
  }
}

// 更新密码
const updatePassword = async () => {
  if (!oldPassword.value) {
    showToast('请输入原密码')
    return
  }
  if (!newPassword.value) {
    showToast('请输入新密码')
    return
  }
  if (newPassword.value.length < 6) {
    showToast('密码长度不能小于6位')
    return
  }
  if (newPassword.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致')
    return
  }
  if (!passwordSmsCode.value) {
    showToast('请输入验证码')
    return
  }
  
  try {
    const res = await updateUserPassword({
      id: userInfo.value.id,
      oldPassword: oldPassword.value,
      newPassword: newPassword.value,
      mobileCode: passwordSmsCode.value,
      mobile: userInfo.value.mobile
    })
    
    if (res.code === 200) {
      showToast('修改成功')
      showPassword.value = false
      showDialog({
        title: '提示',
        message: '密码修改成功，请重新登录',
        showCancelButton: false,
      }).then(() => {
        sessionStorage.clear()
        router.replace('/')
      })
    } else {
      showToast(res.message || '修改失败')
    }
  } catch (error) {
    showToast('修改失败')
  }
}

// 更新昵称
const updateName = async () => {
  if (!newName.value.trim()) {
    showToast('请输入昵称')
    return
  }
  
  try {
    let res = await updateUserName({
      id: userInfo.value.id, 
      name: newName.value
    })
    if(res.code === 200) {
      userInfo.value.name = newName.value
      sessionStorage.setItem('user', JSON.stringify(userInfo.value))
      showToast('修改成功')
      showName.value = false
    } else {
      showToast(res.message || '修改失败')
    }
  } catch (error) {
    showToast('修改失败')
  }
}
</script>

<style scoped>
.user-info-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.info-list {
  margin-top: 12px;
}

.popup-content {
  padding-bottom: 20px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.popup-header .van-icon {
  cursor: pointer;
  font-size: 20px;
  color: #666;
}

.popup-body {
  padding: 20px 16px;
}

.popup-body .van-button {
  margin-top: 20px;
}
</style>
